import math


def neg_x_log(x):
    """

    Args:
        x: a real number

    Returns:
        :math:`- x \cdot \log_2 x`
    """
    assert x >= 0.0
    if x == 0.0:
        return 0.0
    else:
        return - x * math.log(x, 2)


def binary_entropy(p):
    """

    Args:
        p: a real number in [0, 1]

    Returns:
        :math:`H(p) := - p \cdot \log_2 p - (1-p) \cdot \log_2 (1-p)`
    """
    return neg_x_log(p) + neg_x_log(1.0 - p)
